#define _CRT_SECURE_NO_WARNINGS

#include "ALL.h"

void HeapInit(Heap* php)
{
	assert(php);

	php->a = NULL;
	php->capacity = php->size = 0;
}

void swap(int* a, int* b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
}

void adjustup(DataType* a, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] > a[parent])
		{
			swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else break;
	}
}

void adjustdown(DataType* a, int n, int parent)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child + 1] > a[child]) child++;
		if (a[child] > a[parent])
		{
			swap(&a[child], &a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else break;
	}
}

void HeapPush(Heap* php, DataType x)
{
	assert(php);

	if (php->size == php->capacity)
	{
		int newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		DataType* tmp = (DataType*)realloc(php->a, sizeof(DataType) * newcapacity);
		assert(tmp);
		php->a = tmp;
		php->capacity = newcapacity;
	}

	php->a[php->size++] = x;

	adjustup(php->a, php->size - 1);
}

void HeapPop(Heap* php)
{
	assert(php && !HeapEmpty(php));

	swap(&php->a[0], &php->a[php->size - 1]);
	php->size--;

	adjustdown(php->a, php->size, 0);
}

bool HeapEmpty(Heap* php)
{
	assert(php);
	
	return php->size == 0;
}

DataType HeapTop(Heap* php)
{
	assert(php && !HeapEmpty(php));

	return php->a[0];
}

int HeapDataSize(Heap* php)
{
	assert(php);

	return php->size;
}

void HeapDestroy(Heap* php)
{
	assert(php);

	free(php->a);
	php->capacity = php->size = 0;
}

void HeapSort(DataType* a, int n)
{
	assert(a);

	for (int i = (n - 2) / 2; i >= 0; i--) adjustdown(a, n, i);

	int end = n - 1;
	while (end > 0)
	{
		swap(&a[0], &a[end]);
		adjustdown(a, end, 0);
		end--;
	}
}

void HeapTopK(DataType* a, int n, int k)
{
	DataType* topk = (DataType*)malloc(sizeof(DataType) * k);
	assert(topk);

	for (int i = 0; i < k; i++) topk[i] = a[i];

	for (int i = (k - 2) / 2; i >= 0; i--) adjustdown(topk, k, i);

	for (int i = k; i < n; i++)
	{
		if (a[i] < topk[0])
		{
			topk[0] = a[i];
			adjustdown(topk, k, 0);
		}
	}

	for (int i = 0; i < k; i++) printf("%d ", topk[i]);
	printf("\n");

	free(topk);
}